package com.zang.im.croom.netty;

import com.zang.im.croom.netty.handler.WsJsonMsgHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * channel 配置，用于配置请求和编解码
 * @author Zhang Qiang
 * @Date 2019/7/23 19:05
 */
@Component
public class ServerSocketChannelInit extends ChannelInitializer<SocketChannel> {

    @Autowired
    WsJsonMsgHandler wsJsonMsgHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();

        // 60*5 秒客户端没有向服务器发送心跳则关闭连接
        pipeline.addLast(new IdleStateHandler(60*5, 0, 0));
        // HTTP请求的解码和编码
        pipeline.addLast("http-codec", new HttpServerCodec());

        // 把多个消息转换为一个单一的FullHttpRequest或是FullHttpResponse，
        // 原因是HTTP解码器会在每个HTTP消息中生成多个消息对象HttpRequest/HttpResponse,HttpContent,LastHttpContent
        pipeline.addLast("aggregator", new HttpObjectAggregator(65536));

        // 主要用于处理大数据流，比如一个1G大小的文件如果你直接传输肯定会撑暴jvm内存的; 增加之后就不用考虑这个问题了
        pipeline.addLast("http-chunked", new ChunkedWriteHandler());
        // 协议包长度限制
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws", null, true));

        pipeline.addLast("handle", wsJsonMsgHandler);
    }

}
